﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Drawing;
using GSLMS.Core;

namespace GSLMS.WebAPP
{

    /// <summary>  

    /// 单文件上传类 (暂时不支持多文件上传)  

    /// </summary>  

    public class UploadFileManage : IDisposable
    {
        /// <summary>  
        /// 上传文件信息 (动态数组)  
        /// </summary>  
        public Dictionary<string, dynamic> FileInfo = new Dictionary<string, dynamic>();

        /// <summary>
        /// 是否保留源文件名
        /// </summary>
        public bool IsResetSourceName { get; set; }

        /// <summary>  
        /// 最大文件大小  
        /// </summary>  
        public int FileSize = 0;



        /// <summary>
        /// 文件保存路径
        /// </summary>
        public string FilePath = "\\Upload";

        /// <summary>  
        /// 允许上传的文件类型, 逗号分割,必须全部小写!  
        /// 格式: .jpeg|.jpg|.gif|.rar|.zip|.doc 
        /// </summary>  
        public static string FileType = "*";



        /// <summary>  
        /// 上传错误  
        /// </summary>  
        public bool Error;

        /// <summary>
        /// 是否分类存放
        /// </summary>
        public string ClassType { get; set; }

        // public bool IsCutImg { get; set; }

        /// <summary>  
        /// 消息  
        /// </summary>  
        public string Message;

        HttpPostedFileBase PostFile = null;
        //public UploadFileManage(string FormField)
        //{
        //    var Response = HttpContext.Current.Response;
        //    var Request = HttpContext.Current.Request;

        //    // 获取上传的文件  
        //    HttpFileCollection File = Request.Files;
        //    PostFile = File[FormField];

        //}
        static UploadFileManage()
        {
            FileType = System.Web.Configuration.WebConfigurationManager.AppSettings["FileType"] ?? "*";
        }

        public UploadFileManage(HttpPostedFileBase postFile)
        {
            this.PostFile = postFile;
            this.Height = Helper.PhotoHeight;
            this.Width = Helper.PhotoWidth;
            this.Mode = Helper.PhotoCutMode;
        }
        public UploadFileManage() { }
        /// <summary>  
        /// 保存文件  
        /// </summary>  
        public void Save()
        {

            // 验证格式  
            this.CheckingType(PostFile.FileName);
            if (!this.Error)
            {
                // 获取存储目录
                var Path = this.GetPath(PostFile.FileName);
                var dir = Path + this.FileInfo["Name"];
                var sdir = Path + this.FileInfo["SName"];//缩略图
                // 注册文件信息  
                this.FileInfo.Add("path", Path + this.FileInfo["Name"]);
                this.FileInfo.Add("filepath", this.FileInfo["dir"] + this.FileInfo["Name"]);

                // 保存文件
                PostFile.SaveAs(dir);
                if (PostFile.ContentType.IndexOf("image") >= 0)
                {
                    //保存缩略图
                    CompressImage(sdir);
                }
            }
        }



        /// <summary>  
        /// 获取目录  
        /// </summary>  
        /// <returns></returns>  
        private string GetPath(string fileName)
        {
            // 存储目录  
            string Path = this.FilePath;
            // 目录格式  
            string Date = DateTime.Now.ToString("yyyyMMdd");
            string tempPath = string.IsNullOrEmpty(ClassType) ? Path + "\\" + Date : Path + "\\" + ClassType + "\\" + Date + "\\";
            string resourcename = ReSourceName(fileName);
            if (!string.IsNullOrEmpty(resourcename))
            { tempPath += resourcename; }
            string dir = HttpContext.Current.Server.MapPath(tempPath);

            // 注册文件信息  
            this.FileInfo.Add("dir", tempPath.Replace("\\", "/"));
            // 创建目录  
            if (Directory.Exists(dir) == false)
                Directory.CreateDirectory(dir);

            return dir + '/';

        }



        /// <summary>  
        /// 验证文件类型  
        /// </summary>  
        /// <param name="FileName"></param>  
        private void CheckingType(string FileName)
        {

            // 获取允许允许上传类型列表  
            string[] TypeList = FileType.Split('|');
            // 获取上传文件类型(小写)  
            string Type = Path.GetExtension(FileName).ToLowerInvariant();
            string Name = Path.GetFileNameWithoutExtension(FileName);
            string NameHash = Name.GetHashCode().ToString();
            string newFileName = Helper.MD5(NameHash) + "_B" + Type;
            if (IsResetSourceName)
            {
                newFileName = FileName;
            }

            // 注册文件信息  
            this.FileInfo.Add("name", Name);
            this.FileInfo.Add("Name", newFileName);
            this.FileInfo.Add("SName", Helper.MD5(NameHash) + "_S" + Type);
            this.FileInfo.Add("type", Type);
            // 验证类型
            if (!TypeList.Contains("*") && !TypeList.Contains(Type))
                this.TryError("文件类型非法!");

        }

        string ReSourceName(string FileName)
        {
            string Type = Path.GetExtension(FileName).ToLowerInvariant();
            string Name = Path.GetFileNameWithoutExtension(FileName);
            string NameHash = Name.GetHashCode().ToString();
            string newFileName = "";
            if (IsResetSourceName)
            {
                newFileName = Helper.MD5(NameHash) + "\\";
            }
            return newFileName;
        }

        /// <summary>  
        /// 抛出错误  
        /// </summary>  
        /// <param name="Msg"></param>  
        public void TryError(string Msg)
        {
            this.Error = true;
            this.Message = Msg;
        }

        int width = 200;
        /// <summary>
        /// 裁剪的宽度
        /// </summary>
        public int Width
        {
            get { return width; }
            set { width = value; }
        }

        int height = 200;
        /// <summary>
        /// 裁剪的高度
        /// </summary>
        public int Height
        {
            get { return height; }
            set { height = value; }
        }

        string mode = "CUT";
        /// <summary>
        /// 裁剪模式
        /// W": 指定宽，高按比例 
        /// "H": 指定高，宽按比例
        /// "Cut":指定高宽裁减
        /// </summary>
        public string Mode
        {
            get { return mode; }
            set { mode = value; }
        }

        //int with, int height, string mode


        #region 当为图片类型时生成缩略图并保存
        /// <summary>
        /// 当为图片类型时生成缩略图并保存
        /// </summary>
        /// <param name="absloutePath">保存图片的绝对路径</param>

        public int CompressImage(string absloutePath)
        {

            int flag = -1;

            int currentWith = this.Width;               //新图片的宽度
            int currentHeight = this.Height;           //新图片的高度

            //获取原图片变量
            System.Drawing.Image origImag = null;

            //新建一个bmp图片
            System.Drawing.Image bitMap = null;

            //新建一个画板
            System.Drawing.Graphics grap = null;

            int x = 0;              //原图片开始位置（x） 
            int y = 0;              //原图片开始位置（y） 
            int origWith;           //原图片的宽度
            int origHeight;         //原图片的高度

            try
            {
                origImag = System.Drawing.Image.FromStream(this.PostFile.InputStream);

                origWith = origImag.Width;
                origHeight = origImag.Height;

                switch (Mode.ToUpper())
                {
                    case "W":
                        currentHeight = origImag.Height * this.Width / origImag.Width;
                        break;
                    case "H":
                        currentWith = origImag.Width * this.Height / origImag.Height;
                        break;
                    case "CUT":
                        if ((double)origImag.Width / (double)origImag.Height > (double)this.Width / (double)height)
                        {
                            origHeight = origImag.Height;
                            origWith = origImag.Height * this.Width / this.Height;

                            y = 0;
                            x = (origImag.Width - origWith) / 2;
                        }
                        else
                        {
                            origWith = origImag.Width;
                            origHeight = origImag.Width * this.Height / this.Width;

                            x = 0;
                            y = (origImag.Height - origHeight) / 2;
                        }
                        break;
                    default:
                        break;
                }

                //新建一个bmp图片
                bitMap = new System.Drawing.Bitmap(currentWith, currentHeight);

                //新建一个画板
                grap = System.Drawing.Graphics.FromImage(bitMap);

                //设置高质量插值法
                grap.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                //设置高质量,低速度呈现平滑程度
                grap.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //清空画布并以透明背景色填充
                grap.Clear(Color.Transparent);

                //在指定位置并且按指定大小绘制原图片的指定部分
                grap.DrawImage(origImag, new Rectangle(0, 0, currentWith, currentHeight), new Rectangle(x, y, origWith, origHeight), GraphicsUnit.Pixel);

                //保存图片
                bitMap.Save(absloutePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                flag = 1;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                origImag.Dispose();
                bitMap.Dispose();
                grap.Dispose();
            }
            return flag;
        }
        #endregion

        #region 删除文件，成功返回1，失败返回-1
        /// <summary>
        /// public int DeleteFile()
        /// 删除文件，成功返回1，失败返回-1
        /// </summary>
        /// <returns>成功返回1，失败返回-1</returns>
        public int DeleteFile(string path)
        {
            int flag = -1;
            try
            {
                if (path.ToLower().IndexOf("default.") < 0)
                {
                    //删除原文件
                    System.IO.File.Delete(HttpContext.Current.Server.MapPath(path));
                    //当为图片类型且有缩略图时删除缩略图
                    System.IO.File.Delete(HttpContext.Current.Server.MapPath(path.Replace("_B.", "_S.")));
                    flag = 1;
                }
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.ToString());
            }
            finally
            {
            }
            return flag;
        }
        #endregion

        public void Dispose()
        { }
    }

}
